<script setup lang="ts">
import {onMounted, ref} from "vue";
import {useDownPhotosAPI} from '@/apis/equipment.ts';
import  {saveAs} from 'file-saver';
import {ElMessage,ElMessageBox} from "element-plus";
import {useMenuStore} from '@/stores/menuStore.ts'
import {userPermissionStore} from '@/stores/userPermissionStore.ts';
import router from "@/router/index.ts";
import {useEquipmentStore} from '@/stores/equipmentStore.ts';
import {RouteParamValue, useRoute} from "vue-router";

const route=useRoute();

const equipmentStore=useEquipmentStore();
// 获取选择菜单
const menuStore=useMenuStore();
// 这个是控制下面菜单项需要显示的按钮，通过pid和level控制
menuStore.getMenuByPidLevel(5,3);


const permissionStore=userPermissionStore();
permissionStore.getUserPermissionList();


const oneEquipment=ref<any>({});
const srcList=ref<any>([]);


onMounted(async ()=>{
  if (route.params.id===null||route.params.id===undefined){
    await router.push({path:'/home/equipment'})
  }
  else{
    await equipmentStore.getOneByIdStore(route.params.id);
    oneEquipment.value=equipmentStore.equipmentData;
    if (oneEquipment.value.equipmentPhotoList.length>0){
      for (let i = 0; i < oneEquipment.value.equipmentPhotoList.length; i++) {
        srcList.value.push(oneEquipment.value.equipmentPhotoList[i].photoUrl)
      }
    }
  }

})

// 时间戳变成真实时间
function getDate(time: number) {
  let date = new Date(time);
  let Y=date.getFullYear()+'年';
  let M=(date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '月';
  let D=date.getDate()+'日';
  let h=date.getHours()+'时';
  let m=date.getMinutes()+'分';
  return Y+M+D+h+m;
}

// 专门修正element-ui中图片预览必须要从第一张开始的bug
function  getPreviewImgList (index:number) {
  let arr = [];
  for (let i = 0; i < srcList.value.length; i++) {
    arr.push(srcList.value[i + index]);
    if (i + index >= srcList.value.length - 1) { // 为了取后边小值（采用绝对值）
      index = 0 - (i + 1);
    }
  }
  return arr;
}
//
const downPhotos=async ()=>{
  const res=  await useDownPhotosAPI(srcList.value);
  if (res.size>=30)
    saveAs(res,`${oneEquipment.eqName}.zip`);
  else {
    ElMessage({
      message:'没有图片，不能下载',
      type:'warning'
    })
  }
}

const handleClick=async (item: any, id: string | RouteParamValue[])=>{
  if (item.path.includes('/home/equipment/modifyOne'))
  {
    await  router.push({path:'/home/equipment/modifyOne'});
  }
  else if (item.path.includes('/home/equipment/scrap')){
    await  ElMessageBox.confirm(
        '本次操作将会把本设备变更成已报废状态. 是否继续?',
        'Warning',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )
        .then(async () => {
          console.log('设备报废,status变更为2');
          let formData=new FormData();
          formData.append('id',<string>id);
          formData.append('status',2);
          await  equipmentStore.modifyStatus(formData);
          await  router.push({'path':'/home/equipment/'});
          ElMessage({
            type: 'success',
            message: '变更完成',
          })
          await  router.replace({path:'/home/equipment'})
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '取消了变更',
          })
        })
  }

  else if (item.path.includes('/home/equipment/sell')){
    await  ElMessageBox.confirm(
        '本次操作将会把本设备变更成已出售状态. 是否继续?',
        'Warning',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )
        .then(async () => {
          console.log('出售设备，status变更为3');
          let formData2=new FormData();
          formData2.append('id',<string>id);
          formData2.append('status',3);
          await  equipmentStore.modifyStatus(formData2);
          await  router.push({'path':'/home/equipment/'});
          ElMessage({
            type: 'success',
            message: '变更完成',
          })
          await  router.replace({path:'/home/equipment'})
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '取消了变更',
          })
        })
  }

  else {
    await  ElMessageBox.confirm(
        '本次操作将删除本表单. 是否继续?',
        'Warning',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )
        .then(async () => {
          await equipmentStore.deleteOneById(id);
          ElMessage({
            type: 'success',
            message: '删除完成',
          })
          await  router.replace({path:'/home/equipment'})
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '取消了删除',
          })
        })
  }

}

</script>

<template>
  <!-- 面包屑 -->
  <div class="bread-container">
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: `/` }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{path:`/home/equipment`}" >设备主页</el-breadcrumb-item>
      <el-breadcrumb-item  >设备详细页</el-breadcrumb-item>
    </el-breadcrumb>
  </div>

  <div class="divTable">

    <table class="table">
      <tbody>
      <tr>
        <td class="tableTitle" colspan="4" >设    备    详    细    信    息</td>
      </tr>
      <tr>
        <td style="width: 250px;height: 15px;text-align: center;background: #EFF6FF;color: #242424;font-family: 微软雅黑,serif">设备名称</td>
        <td style="width: 350px;height: 15px;   text-align: center  ">{{oneEquipment.eqName}}</td>
        <td style="width: 250px;height: 15px; text-align: center ;background: #EFF6FF"  >设备品牌</td>
        <td style="width: 350px;height: 15px ; text-align: center   ">{{oneEquipment.brand}}</td>
      </tr>
      <tr>
        <td style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">设备型号</td>
        <td style="width: 350px;height: 15px;text-align: center  ">{{oneEquipment.model}}</td>
        <td style="width: 250px;height: 15px;text-align: center ;background: #EFF6FF"  >设备编码</td>
        <td style="width: 350px;height: 15px;text-align: center   ">{{oneEquipment.encode}}</td>
      </tr>
      <tr>
        <td style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">设备数量单位</td>
        <td style="width: 350px;height: 15px;text-align: center  ">{{oneEquipment.pieces}}</td>
        <td style="width: 250px;height: 15px;text-align: center ;background: #EFF6FF"  >设备数量</td>
        <td style="width: 350px;height: 15px;text-align: center   ">{{oneEquipment.number}}</td>
      </tr>
      <tr>
        <td style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">设备类型</td>
        <td style="width: 350px;height: 15px;text-align: center  ">{{oneEquipment.typeName}}</td>
        <td style="width: 250px;height: 15px;text-align: center ;background: #EFF6FF"  >设备所在地</td>
        <td style="width: 350px;height: 15px;text-align: center   ">{{oneEquipment.location}}</td>
      </tr>
      <tr>
        <td  style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">备注</td>
        <td colspan="3" style="width: 850px;height: 15px;text-align: center">{{oneEquipment.description}}</td>
      </tr>
      <tr>
        <td style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">创建人</td>
        <td style="width: 350px;height: 15px;text-align: center  ">{{oneEquipment.createBy}}</td>
        <td style="width: 250px;height: 15px;text-align: center ;background: #EFF6FF"  >最后修改人</td>
        <td style="width: 350px;height: 15px;text-align: center   ">{{oneEquipment.lastUpdateBy}}</td>
      </tr>
      <tr>
        <td style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">创建时间</td>
        <td style="width: 350px;height: 15px;text-align: center  ">{{getDate(oneEquipment.createTime)}}</td>
        <td style="width: 250px;height: 15px;text-align: center ;background: #EFF6FF"  >最后修改时间</td>
        <td style="width: 350px;height: 15px;text-align: center   ">{{ getDate(oneEquipment.updateTime)}}</td>
      </tr>
      <tr>
        <td colspan="4" style="width: 250px;height: 15px;text-align: center;background: #EFF6FF"></td>
      </tr>
      <tr>
        <td style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">图片资料</td>
        <td  colspan="3" style="width: 350px;height: 15px;text-align: center  ">
          <br>
          <div class="demo-image__preview">
            <el-image v-for="(ele,index) in srcList" :key="index"
                      style="width: 200px; height: 200px"
                      :src="ele"
                      :zoom-rate="1.2"
                      :max-scale="5"
                      :min-scale="0.5"
                      :preview-src-list="getPreviewImgList(index)"
                      fit="cover"
            />
          </div>
          <el-button link type="primary" @click="downPhotos" >打包下载</el-button>
          <br>
        </td>
      </tr>
      <tr>
        <td colspan="4" style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">
          <el-button
              v-if="permissionStore.flag"
              type="warning"
              v-for="(item,index) in menuStore.choseMenu"
              :key="index"
              @click="handleClick(item,route.params.id)"
          >
            {{item.title}}
          </el-button>
        </td>
      </tr>
      </tbody>
    </table>
  </div>
</template>


<style scoped lang="scss">
.bread-container {
  padding: 25px 10px;
  margin-left: 10px;
}
.divTable {
  position: absolute;
  top: 150px;
  bottom: 0;
  left: 300px;
  right: 0;
  margin: auto;
}


table, td,tr{
  border: 1px solid #44a8da;
  text-align: center;
  border-spacing: 0;
  border-collapse: collapse;
  height: 45px;
}

.tableTitle{

  border-right: 0 none;
  border-left: 0 none;
  text-align: center;
  font-size: large;
  font-weight: bold;
}

.demo-image__error .image-slot {
  font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}
.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}

</style>